package com.contract.config;


import com.alibaba.fastjson.JSON;
import com.contract.common.enums.RegisterTypeEnum;
import com.contract.common.error.BizException;
import com.contract.common.error.JsonReturnCode;
import com.contract.common.util.JwtUtil;
import com.contract.pojo.dto.UserAuth;
import com.contract.service.common.LoginUser;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 权限管理配置
 *
 * @author liw
 * @version 1.0
 * @date 2022/8/28 15:20
 */
@Component
//这里采用继承OncePerRequestFilter的方式来自定义过滤器，而不使用实现Filter接口的方式，原因是前一种方式可以避免请求被多次拦截
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //1.获取token
        String token = httpServletRequest.getHeader("token");
        if (token == null || token.trim().isEmpty()) {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        //2.解析token
        String userInfo;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            userInfo = claims.getSubject();
        } catch (Exception e) {
//            e.printStackTrace();
            throw new BizException(JsonReturnCode.TOKEN_GET_ERR);
        }
        //3.获取用户信息
        LoginUser loginUser = JSON.parseObject(userInfo, LoginUser.class);
        if (Objects.isNull(userInfo)) {
            throw new BizException(JsonReturnCode.TOKEN_ERR);
        }

        List<String> permList = new ArrayList<>();
        String type = loginUser.getUser().getType();
        permList.add("register_info");
        permList.add("file_upload");
        permList.add("file_download");
        permList.add("contract_list");
        if (type.equals(RegisterTypeEnum.U.getKey())) {
            permList.add("register_check_face");
            permList.add("register_card_face");
            permList.add("register_card_back");
            permList.add("register_save");
            permList.add("contract_sign");
            permList.add("register_info_non");
        } else if (type.equals(RegisterTypeEnum.M.getKey())) {
            permList.add("user_list");
            permList.add("user_info");
            permList.add("user_delete");
            permList.add("register_list");
            permList.add("register_approved");
            permList.add("register_reject");
            permList.add("home_statistics");
            permList.add("home_carousel");
            permList.add("home_chart");
            permList.add("template_list");
            permList.add("template_info");
            permList.add("template_save");
            permList.add("contract_save");
            permList.add("contract_invalid");
            permList.add("contract_stamp");
            permList.add("contract_preview");
            permList.add("contract_delete");
        }

        // 把权限放入user
        List<UserAuth> list = new ArrayList<>(permList.size());
        for (String s : permList) {
            UserAuth auth = new UserAuth();
            auth.setPerms(s);
            list.add(auth);
        }
        loginUser.setPermissions(list);

        //4.存入SecurityContextHolder
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities()));
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
}
